﻿using System;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Descripción breve de CObtenerId
/// </summary>
namespace consultasSql.consultasVarias
{
    public class CObtenerId : CDarDataSet
    {
        public string obtenerId(string tabla, string campo, string dato)
        {
            string id = "";

            if (!String.IsNullOrEmpty(tabla) && !String.IsNullOrEmpty(campo) && !String.IsNullOrEmpty(dato))
            {
                id = obtener(tabla, campo, dato);
            }

            return id;
        }

        private string obtener(string tabla, string campo, string dato)
        {
            SqlCommand command = new SqlCommand();

            command.CommandType = CommandType.Text;
            command.CommandText = "SELECT TOP 1 Id FROM " + tabla + " WHERE " + campo + " = @dato";

            command.Parameters.Clear();

            command.Parameters.AddWithValue("@dato", dato.Trim());


            DataTable dt = darDataTable(command);

            if (dt != null)
            {
                try
                {
                    if (dt.Rows[0][0] == null)
                        return null;
                    else
                        return Convert.ToString(dt.Rows[0][0]);
                }
                catch
                {
                }
            }
            return null;
        }
    }
}